import { getBaseURLWS } from '@/assets/js/config'; // 引入获取基础URL的函数

const baseURL = `${getBaseURLWS()}/ws/chat_ai?token=${localStorage.getItem("token")}`;

class WebSocketService {
    constructor() {
        this.socket = null; // 当前 WebSocket 实例
        this.WEBSOCKET_URL = `${baseURL}`;
        this.onMessageCallback = null; // 消息回调函数（由外部提供）

        // 自动重连参数
        this.reconnectDelay = 2000;           // 初始重连间隔（毫秒）
        this.maxReconnectDelay = 30000;       // 最大重连间隔 （毫秒）
        this.reconnectAttempts = 0;           // 当前重连尝试次数
        this.shouldReconnect = true;          // 是否允许自动重连
        this.isConnecting = false;
    }

    /**
     * 建立 WebSocket 连接，并绑定消息处理回调函数
     * @param {Function} onMessageCallback 外部传入的消息处理函数
     */
    connect(onMessageCallback) {
        const token = localStorage.getItem("token");

        if (!token) {
            console.warn("⚠️ 当前未登录，服务器无法连接...");
            this.shouldReconnect = false;
            window.location.href = '/login';  // 👈 跳转登录页
            return;
        }

        if (this.isConnecting || (this.socket && this.socket.readyState === WebSocket.OPEN)) {
            return; // 避免重复发起连接
        }

        this.isConnecting = true;
        this.onMessageCallback = onMessageCallback;
        this.WEBSOCKET_URL = `${getBaseURLWS()}/ws/chat_ai?token=${localStorage.getItem("token")}`;

        console.log('正在尝试连接服务器...');
        try {
            this.socket = new WebSocket(this.WEBSOCKET_URL);
        } catch (error) {
            console.error('服务器异常，连接服务器失败:', error);
            this.isConnecting = false;
            if (this.shouldReconnect) {
                this.reconnect();
            }
            return;
        }

        this.socket.addEventListener('open', () => {
            console.log('✅ 服务器已连接');
            this.reconnectAttempts = 0;
            this.isConnecting = false;
        });

        this.socket.addEventListener('close', () => {
            console.log('❌ 服务器异常连接关闭');
            this.isConnecting = false;
            if (this.shouldReconnect) {
                this.reconnect();
            }
        });

        this.socket.addEventListener('error', (event) => {
            console.log('⚠️ 服务器异常连接关闭:', event);
            this.isConnecting = false;
            if (this.shouldReconnect) {
                this.reconnect();
            }
        });

        this.socket.addEventListener('message', (event) => {
            if (typeof this.onMessageCallback === 'function') {
                this.onMessageCallback(JSON.parse(event.data));
            }
        });
    }


    /**
     * 自动重连逻辑，支持指数回退（最多不超过 maxReconnectDelay）
     */
    reconnect() {
        const token = localStorage.getItem("token");
        if (!token) {
            console.warn("⚠️ 无 token，取消重连并跳转登录页");
            this.shouldReconnect = false;
            window.location.href = '/login';
            return;
        }
        
        if (this.reconnectAttempts > 15) {
            console.warn("❌ 重连次数过多，已放弃");
            return;
        }

        this.reconnectAttempts++;
        const delay = Math.min(this.reconnectDelay * this.reconnectAttempts, this.maxReconnectDelay);

        setTimeout(() => {
            this.connect(this.onMessageCallback);
        }, delay);
    }


    /**
     * 向服务器发送消息（仅当连接状态为 OPEN）
     * @param {Object} message 要发送的消息对象
     */
    sendMessage(message) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify(message));
        } else {
            console.log('📪 WebSocket未连接，消息发送失败');
        }
    }

    /**
     * 主动关闭连接并停止后续自动重连
     */
    close() {
        this.shouldReconnect = false;
        if (this.socket) {
            this.socket.close();
        }
    }


}

export default WebSocketService;
